package com.biostime.springdraw.modules.sd.web;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.biostime.springdraw.common.config.Global;
import com.biostime.springdraw.common.persistence.Page;
import com.biostime.springdraw.common.utils.StringUtils;
import com.biostime.springdraw.common.web.BaseController;
import com.biostime.springdraw.modules.sd.dto.DistributedAwardDto;
import com.biostime.springdraw.modules.sd.entity.Award;
import com.biostime.springdraw.modules.sd.entity.Section;
import com.biostime.springdraw.modules.sd.service.AwardService;
import com.biostime.springdraw.modules.sd.service.DrawService;
import com.biostime.springdraw.modules.sd.service.SectionService;
import com.biostime.springdraw.modules.sd.service.ShareawardService;
import com.biostime.springdraw.modules.sd.service.WinnerService;
import com.biostime.springdraw.modules.sys.entity.User;

/**
 * 奖品阶段表Controller
 * @author king
 * @version 2016-01-18
 */
@Controller
@RequestMapping(value = "${adminPath}/sd/section")
public class SectionController extends BaseController {

	@Autowired
	private SectionService sectionService;
	@Autowired
	private AwardService awardService;
	@Autowired
	private WinnerService winnerService;
	@Autowired
	private DrawService drawService;
	@Autowired
	private ShareawardService shareawardService;
	
	@ModelAttribute
	public Section get(@RequestParam(required=false) String id) {
		Section entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = sectionService.get(id);
		}
		if (entity == null){
			entity = new Section();
		}
		return entity;
	}

	@RequiresPermissions("sd:section:view")
	@RequestMapping(value = {"list", ""})
	public String list(Section section, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<Section> page = sectionService.findPage(new Page<Section>(request, response), section); 
		List<Section> list = page.getList();
		if(list != null && !list.isEmpty()){
			for(Section s : list){
				if(s.getSections() != null && !s.getSections().isEmpty()){
					Section s2 = s.getSections().get(0);
					s.setGlobalRate(s2.getGlobalRate()); 
					s.setName(s2.getName());
					s.setStartOn(s2.getStartOn());
					s.setEndOn(s2.getEndOn());
				}
			}
		}
		page.setList(list);
		model.addAttribute("page", page);
		return "modules/sd/sectionList";
	}
	
	@RequiresPermissions("sd:section:view")
	@RequestMapping(value = "form")
	public String form(Section section, Model model) {
		List<Award> awards = awardService.findList(new Award());
		List<Section> sections = sectionService.findListByName(section);
		
		if(sections != null && !sections.isEmpty()){
			
			//获取某阶段奖品总数
			int sectionSum = 0;
			
			//奖品分享数量(电影票的分享数量)
			int shareNum = 0;
			Award a = null;
			for (int j = 0; j < sections.size(); j++) {
				sectionSum += sections.get(j).getAmount();
				a = awardService.get(String.valueOf(sections.get(j).getAwardId()));
				if(a.getAwardtype().getType().equals("moviecode")){
					shareNum = sections.get(j).getAmount();
				}				
			}			
							
			//设置奖品数量
			for (int i = 0; i < awards.size(); i++) {
				Award temp = awards.get(i);
				
				//某奖品数量
				int sectionNum = 0;
					
				//设置伪库存
				temp.setStock(temp.getAmount()-winnerService.getWinnerCount(temp));
				
				//设置真库存
				String sectionCode = sections.get(0).getCode();
				int shareExistsAward = shareawardService.shareExitsOneAward(sectionCode, awards.get(i).getId()); 
				temp.setRealStock(temp.getAmount()-winnerService.getWinnerCount(temp) - shareExistsAward); 
				
				//遍历某阶段的奖品
				for (int j = 0; j < sections.size(); j++) {
					if(temp.getId().equals(String.valueOf(sections.get(j).getAwardId()))){
						sectionNum = sections.get(j).getAmount();
						temp.setSectionNum(sectionNum);
						break;
					}
				}		
							
				//设置概率
				if(sectionSum == 0){
					temp.setRate(0);
				}else{
					double   f   =   sectionNum/(double)sectionSum;  
					BigDecimal   b   =   new   BigDecimal(f);  
					double   f1   =   b.setScale(5,   BigDecimal.ROUND_HALF_UP).doubleValue();  
					temp.setRate(f1);
				}
				awards.set(i,temp);
			}
			
			//已分发奖品列表
			if(sections != null && !sections.isEmpty()){
				drawService.awardRange(sections);
				List<DistributedAwardDto> awardDtoList= winnerService.getSectionAwards(sections.get(0).getCode(),2);	
				DistributedAwardDto drawAward = null;
				int sectionDistributed = 0;
				int sectionDrawAward = 0;
				int sectionShareAward = 0;
				for(Award award : awards){
					if(awardDtoList != null && !awardDtoList.isEmpty()){				
						for(DistributedAwardDto awardDto : awardDtoList){
								if(award.getId().equals(String.valueOf(awardDto.getAwardId()))){					
									drawAward = winnerService.getSectionDrawAwards(sections.get(0).getCode(),award.getId(),0);								
									sectionDistributed = awardDto.getSum();
									sectionDrawAward = drawAward.getSum();
									sectionShareAward = sectionDistributed-sectionDrawAward;
									
									logger.info("抽奖阶段："+awardDto.getAwardSectionCode()+"------------"+"奖品id:"+awardDto.getAwardId()+"------------"
										+"共中走:"+sectionDistributed	+"------------"+"积分中奖:"+sectionDrawAward+"--------------"+"分享中奖:"+sectionShareAward);	
									
									award.setSectionDistributed(sectionDistributed);	
									award.setSectionDrawAward(sectionDrawAward);
								}
						}					
					}		
					if(award.getIsShare().equals("1"))
						award.setShareNum(shareNum); 
				}			
			}
					
		}
		
		model.addAttribute("awards", awards);
		model.addAttribute("section", section);			
		
		return "modules/sd/sectionForm";
	}

	@RequiresPermissions("sd:section:edit")
	@RequestMapping(value = "save")
	public String save(Section section, HttpServletRequest request, Model model, RedirectAttributes redirectAttributes) {
		
		if (!beanValidator(model, section)){
			return form(section, model);
		}
		String message = "";		
		if(section.getGlobalRate() == null || section.getGlobalRate().equals("")){
			section.setGlobalRate(0d); 
		}
		section.setCreateBy(new User("0"));
		section.setUpdateBy(new User("0"));
		section.setCreateDate(new Date());
		section.setUpdateDate(new Date()); 
		
		//检查结束时间在开始时间之后
		if(!section.getEndOn().after(section.getStartOn())){
			message = "指定结束时间比活动的开始时间早";
			model.addAttribute("message", message);
			return form(section, model);
		}
		
		//检查是否与别的抽奖有时间冲突
		List<Section> dateCheck = sectionService.betweenDate(section);
		if(dateCheck != null && dateCheck.size() != 0){
			for (Section temp : dateCheck) {
				if(!temp.getName().equals(section.getName())){
					message = "时间设置与其他抽奖冲突,请检查!!!";
					model.addAttribute("message", message);
					return form(section, model);
				}
			}
		}
/*		try{*/
			message  = sectionService.saveSection(section);
/*		}catch(Exception e){
			message = "请填写数字";
		}*/
		if(!message.equals("保存成功")){
			model.addAttribute("message", message);
			return form(section, model);
		}
		addMessage(redirectAttributes, "保存成功");
		return "redirect:"+Global.getAdminPath()+"/sd/section/?repage";

	}

	@RequiresPermissions("sd:section:delete")
	@RequestMapping(value = "delete")
	public String delete(@RequestParam(value="ids",required=false) String idsRequest, Section section, RedirectAttributes redirectAttributes) {
		if(!StringUtils.isEmpty(idsRequest)){
			String[] ids = idsRequest.split(",");
			for(String id : ids){
				Section deleteTemp = sectionService.get(id);
				List<Section> list = sectionService.findListByName(deleteTemp);
				for (Section temp : list) {
					sectionService.delete(temp);
				}
			}
		}else{
			List<Section> list = sectionService.findListByName(section);
			for (Section temp : list) {
				sectionService.delete(temp);
			}
		}
		addMessage(redirectAttributes, "删除成功");
		return "redirect:"+Global.getAdminPath()+"/sd/section/?repage";
	}

}